package com.qianwei.footpath.ui;

import static com.qianwei.footpath.utils.Util.calculateBMIExact;
import static com.qianwei.footpath.utils.Util.calculateProgress;
import static com.qianwei.footpath.utils.Util.roundToOneDecimal;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.common.baselib.mvp.MvpBasePresenter;
import com.common.baselib.ui.ToastUtil;
import com.qianwei.footpath.R;
import com.qianwei.footpath.base.BaseActivity;
import com.qianwei.footpath.event.SerialPortEvent;
import com.qianwei.footpath.manage.DataManager;
import com.qianwei.footpath.manage.LocalCacheDataManage;
import com.qianwei.footpath.manage.SerialPortManager;
import com.qianwei.footpath.manage.TimerManager;
import com.qianwei.footpath.utils.TextToSpeechUtils;
import com.qianwei.footpath.utils.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.TimerTask;

public class TestA extends BaseActivity {
    private static final String TAG = "TestA";
    private static final int HEIGHT_MIN_VALUE = 100;
    private static final int HEIGHT_MAX_VALUE = 250;
    private static final int WEIGHT_MIN_VALUE = 30;
    private static final int WEIGHT_MAX_VALUE = 250;
    private static final int BMI_MIN_VALUE = 10;
    private static final int BMI_MAX_VALUE = 40;
    private ImageView ivXuHua, ivYuanhuan, ivRen;
    private TextView ivTitle, tv_result, tvDown;
    private SeekBar sbHeight, sbWeight, sbBmi;
    private TextView tvWeight, tvHeight, tvBmi, tvBmiResult;
    private TimerTask testRealTimeWeightTimeTask, testWeightTimeTask, testHeightTimeTask;
    private TextToSpeechUtils ttsUtils;
    private int testDownLoadTime = 30;
    private double weightResultValue;

    @Override
    protected int layoutId() {
        return R.layout.a_activity;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        ivTitle = findViewById(R.id.ivTitle);
        ivXuHua = findViewById(R.id.ivXuHua);
        ivYuanhuan = findViewById(R.id.ivYuanhuan);
        tvDown = findViewById(R.id.tvDown);
        tv_result = findViewById(R.id.tv_result);
        ivRen = findViewById(R.id.ivRen);
        sbHeight = findViewById(R.id.sb_height);
        sbWeight = findViewById(R.id.sb_weight);
        sbBmi = findViewById(R.id.sb_bmi);
        tvBmi = findViewById(R.id.tvBmi);
        tvBmiResult = findViewById(R.id.tvBmiResult);
        tvWeight = findViewById(R.id.tv_weight);
        tvHeight = findViewById(R.id.tv_height);
        ivRen.setImageResource(R.drawable.ic_ren1);
        ivYuanhuan.setVisibility(View.VISIBLE);
        ivTitle.setText("身高体重测量");
        tv_result.setText("身高体重测量结果");

        testDownLoadTime = LocalCacheDataManage.getLocalConfigData().getPhysical_test_timeout();

        sbHeight.setOnTouchListener((v, e) -> true);
        sbWeight.setOnTouchListener((v, e) -> true);
        sbBmi.setOnTouchListener((v, e) -> true);

        startZoomAnimation();

        initTTS();

    }

    private void initTTS() {
        ttsUtils = new TextToSpeechUtils(this, new TextToSpeechUtils.OnInitListener() {
            @Override
            public void onInitSuccess() {
                speak("请您站在体测仪上，保持平稳，开始测量", "101");
                SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                stopTimeTask(testRealTimeWeightTimeTask);
                startTestRealTimeWeightTimeTask();
            }

            @Override
            public void onInitFailed(int errorCode) {
                Log.e(TAG, "TTS初始化失败");
                showToast("语音播报初始化失败");
                SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                stopTimeTask(testRealTimeWeightTimeTask);
                startTestRealTimeWeightTimeTask();
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRealTimeWeightReceived(SerialPortEvent.RealTimeWeightEvent event) {
        double weight = event.value;
        Log.e(TAG, "测量一次体重完成: " + weight);
        if (weight > 0) {
            stopTimeTask(testRealTimeWeightTimeTask);

            speak("正在测量中，请稍候", "102");
            Log.e(TAG, "发送称重指令");
            SerialPortManager.getInstance(getContext()).sendWeightCommand();
            stopTimeTask(testWeightTimeTask);
            startTestWeightTimeTask();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWeightCompletion(SerialPortEvent.WeightCompletionEvent event) {
        double weight = event.finalValue;
        Log.e(TAG, "体重完成: " + weight);

        stopTimeTask(testWeightTimeTask);
        weightResultValue = roundToOneDecimal(weight);

        tvWeight.setText(String.valueOf(weightResultValue));
        int progress = calculateProgress(weight, WEIGHT_MIN_VALUE, WEIGHT_MAX_VALUE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sbWeight.setProgress(progress, true);
        } else {
            sbWeight.setProgress(progress);
        }

        DataManager.getInstance().setWeightResultValue(weightResultValue);

        new Handler().postDelayed(() -> {
            Log.e(TAG, "发送身高指令");
            SerialPortManager.getInstance(getContext()).sendHeightCommand();

            stopTimeTask(testHeightTimeTask);
            startTestHeightTimeTask();
        }, 500);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHeightCompletion(SerialPortEvent.HeightCompletionEvent event) {
        double height = event.finalValue;
        Log.e(TAG, "身高完成: " + height);
        stopTimeTask(testHeightTimeTask);
        double heightResultValue = roundToOneDecimal(height);
        double bmiResultValue = calculateBMIExact(heightResultValue, weightResultValue);
        String bmiCategory = Util.getBMICategory(bmiResultValue);
//        speak("请您双手紧握把手，开始心率测量", "heart");

        tvHeight.setText(String.valueOf(heightResultValue));
        int heightProgress = calculateProgress(heightResultValue, HEIGHT_MIN_VALUE, HEIGHT_MAX_VALUE);

        int bmiProgress = calculateProgress(bmiResultValue, BMI_MIN_VALUE, BMI_MAX_VALUE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sbHeight.setProgress(heightProgress, true);
            sbBmi.setProgress(bmiProgress, true);
        } else {
            sbHeight.setProgress(heightProgress);
            sbBmi.setProgress(bmiProgress);
        }

        tvBmi.setText(String.valueOf(bmiResultValue));
        tvBmiResult.setText(bmiCategory);

        DataManager.getInstance().setHeightResultValue(heightResultValue);
        DataManager.getInstance().setBmiResultValue(bmiResultValue);
        DataManager.getInstance().setBmiCategory(bmiCategory);

        new Handler().postDelayed(() -> {
            startActivity(new Intent(getContext(), TestB.class));
            finish();
        }, 1000);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onError(SerialPortEvent.ErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：" + event.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProtocolError(SerialPortEvent.ProtocolErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：errorCode=" + event.errorCode + ",errorMsg=" + event.errorMsg);
    }

    private void speak(String text, String utteranceId) {
        ttsUtils.speak(text, utteranceId, null);
    }

    private void speak(String text, String utteranceId, TextToSpeechUtils.OnPlayListener listener) {
        ttsUtils.speak(text, utteranceId, listener);
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    private void startTestRealTimeWeightTimeTask() {
        if (testRealTimeWeightTimeTask == null) {
            Log.e(TAG, "一次体重定时器");
            testRealTimeWeightTimeTask = new TimerTask() {
                private int secondsPassed = 0;

                @Override
                public void run() {
                    secondsPassed++;
                    runOnUiThread(() -> {
                        int dif = testDownLoadTime - secondsPassed;
                        tvDown.setText(dif + "s");
                        if (dif % 2 == 0) {
                            SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                        }
                    });
                    if (secondsPassed >= testDownLoadTime) {
                        finish();
                    }
                }
            };
            TimerManager.getInstance().startTimer(1000, 1000, testRealTimeWeightTimeTask); // 每秒执行一次
        }
    }

    private void startTestWeightTimeTask() {
        if (testWeightTimeTask == null) {
            Log.e(TAG, "体重定时器");
            testWeightTimeTask = new TimerTask() {
                private int secondsPassed = 0;

                @Override
                public void run() {
                    secondsPassed++;
                    runOnUiThread(() -> {
                        int dif = testDownLoadTime - secondsPassed;
                        tvDown.setText(dif + "s");
                    });
                    if (secondsPassed >= testDownLoadTime) {
                        finish();
                    }
                }
            };
            TimerManager.getInstance().startTimer(1000, 1000, testWeightTimeTask);
        }
    }

    private void startTestHeightTimeTask() {
        if (testHeightTimeTask == null) {
            Log.e(TAG, "身高定时器");
            testHeightTimeTask = new TimerTask() {
                private int secondsPassed = 0;

                @Override
                public void run() {
                    secondsPassed++;
                    runOnUiThread(() -> {
                        int dif = testDownLoadTime - secondsPassed;
                        tvDown.setText(dif + "s");
                    });
                    if (secondsPassed >= testDownLoadTime) {
                        finish();
                    }
                }
            };
            TimerManager.getInstance().startTimer(1000, 1000, testHeightTimeTask);
        }
    }


    private void stopTimeTask(TimerTask timerTask) {
        if (timerTask != null) {
            TimerManager.getInstance().stopTimer(timerTask);
            timerTask.cancel();
        }
    }

    private void startZoomAnimation() {
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(ivXuHua, "scaleX", 1f, 1.1f);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(ivXuHua, "scaleY", 1f, 1.1f);
        scaleXAnimator.setDuration(800);
        scaleYAnimator.setDuration(800);
        scaleXAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleYAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleXAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleYAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleXAnimator.setRepeatMode(ValueAnimator.REVERSE);
        scaleYAnimator.setRepeatMode(ValueAnimator.REVERSE);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
        animatorSet.start();
    }


    @Override
    protected void onDestroy() {
        if (ttsUtils != null) {
            ttsUtils.release();
            ttsUtils = null;
        }
        EventBus.getDefault().unregister(this);
        stopTimeTask(testRealTimeWeightTimeTask);
        stopTimeTask(testHeightTimeTask);
        stopTimeTask(testWeightTimeTask);
        super.onDestroy();
    }

    @Override
    protected MvpBasePresenter createPresenter() {
        return null;
    }
}
